package com.ushare.sockets;

import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.channels.*;


public class PeerGroupIDCreatorSocket {


public static String PeerGroupIDCreator() throws Exception{
	String PeerGroupID = null;
	try {
        // Create a non-blocking server socket channel
        ServerSocketChannel sockChannel = ServerSocketChannel.open();
        sockChannel.configureBlocking(false);

        // Set the host and port to monitor 
        InetSocketAddress server = new InetSocketAddress(
            "localhost", 8010);
        ServerSocket socket = sockChannel.socket();
        socket.bind(server);

        // Create the selector and register it on the channel
        Selector selector = Selector.open();
        sockChannel.register (selector, SelectionKey.OP_CONNECT);

        // Loop forever, looking for client connections
        while (true) {
            // Wait for a connection
            selector.select();

            // Get list of selection keys with pending events
            Set keys = selector.selectedKeys();
            Iterator it = keys.iterator();

            // Handle each key
            while (it.hasNext()) {

                // Get the key and remove it from the iteration
                SelectionKey selKey = (SelectionKey) it.next();

                it.remove();
                if (selKey.isAcceptable()) {

                    // Create a socket connection with the client
                    ServerSocketChannel selChannel =
                        (ServerSocketChannel) selKey.channel();
                    ServerSocket selSocket = selChannel.socket();
                    Socket connection = selSocket.accept();

                    // Handle the finger request
                    PeerGroupID = handleRequest(connection);
                    System.out.println(PeerGroupID);
                    connection.close();
                }
            }
         }
     } catch (IOException ioe) {
         System.out.println(ioe.getMessage());
     }
     return PeerGroupID;
 }

private static String handleRequest(Socket connection) throws IOException {

    // Set up input and output
    InputStreamReader isr = new InputStreamReader (connection.getInputStream());
    BufferedReader is = new BufferedReader(isr);
    PrintWriter pw = new PrintWriter(new BufferedOutputStream (connection.getOutputStream()),false);

    // Output server greeting
    pw.println("PeerGroupIDCreator");
    pw.flush();

    // Handle user input
    String outLine = null;
    String inLine = is.readLine();

    if (inLine.length() > 0) {
        outLine = inLine;
    }
    

    // Clean up
    pw.flush();
    pw.close();
    is.close();
    return outLine;
}




    //NewFingerServer nio = new NewFingerServer();

}